﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Consul;
using Microsoft.AspNetCore.Mvc;
using PeerClient_Consul.Models;

namespace PeerClient_Consul.Controllers
{
    /// <summary>
    /// 节点服务  1）包括心跳包的验证  
    ///           2）对其他节点的响应 
    ///           4）了解
    /// </summary>
    public class HomeController : Controller
    {
        static List<string> Urls = new List<string>();
        public IActionResult Index()
        {
            var str = "";
            str += "开始输出当前所有服务地址";
            Catalog_Nodes().GetAwaiter().GetResult();
            //Console.WriteLine(HelloConsul().GetAwaiter().GetResult());
            str += "开始随机请求一个地址服务地址";
            int index = new Random().Next(Urls.Count);
            string url = Urls[index];
            string param = "";//这里是开始位置
            param += "{";
            param += "\"" + "id" + "\":\"" + 5 + "\",";
            param = param.TrimEnd(',');
            param += "}";
            str += "请求的随机地址：" + url;
            string result = HttpClientHelpClass.PostResponse(url, param, out string statusCode);
            str += "返回状态：" + statusCode;
            str += "返回结果：" + result;
            return Content(str);
        }
        public static async Task Catalog_Nodes()
        {
            var client = new ConsulClient();
            var nodeList = await client.Agent.Services();
            var url = nodeList.Response.Values;

            foreach (var item in url)
            {
                string Address = item.Address!=null&&item.Address!=""? item.Address:"127.0.0.1";//暂时
                int port = item.Port;
                string name = item.Service;
                // Console.WriteLine($"地址：{Address}:{port},name：{name}");
                Urls.Add($"http://{Address}:{port}/api/Test");
            }
        }

    }
}
